<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose">
    <el-form :inline="true" :rules="rules" :model="body" ref="queryForm" size="small" label-width="92px">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="类型：" prop="type">
            <el-select v-model="body.type" placeholder="请选择">
              <el-option v-for="item in typeOption" :key="item.id" :label="item.value" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否启用：" prop="isEnabled">
            <el-switch v-model="body.isEnabled" :active-value="1" :inactive-value="2"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="图片路径：" prop="imagePath">
            <!-- <el-input placeholder="请输入路径" v-model="body.imagePath" clearable></el-input> -->
            <el-upload action="/api/upload" list-type="picture-card" :before-upload="beforeUpload"
              :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :headers="headers">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="imgDialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="跳转路径：" prop="jumpUrl">
            <el-input v-model="body.jumpUrl" placeholder="请输入跳转路径" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="显示顺序：" prop="sort">
            <el-input type="number" v-model="body.sort" placeholder="请输入显示顺序" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="描述信息：" prop="description">
            <el-input v-model="body.description" placeholder="请输入描述信息" clearable />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submit('queryForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import axios from 'axios';
import { getBannerTypeCode } from "@/utils/transform/transform"
import { updateBannersApi, addBannersApi } from "@/api/banners/bannerslist"
import { getToken } from "@/utils/auth";
export default {
  name: "BannersDialog",
  props: {
    dialogVisible: {
      type: Boolean,
      require: true
    },
    title: {
      type: String,
      require: true
    },
    bannerInfo: {
      type: Object,
      require: false
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      imgDialogVisible: false,
      headers: {
        Authorization: "Bearer " + getToken()
      },
      body: {
        type: null,
        isEnabled: null,  //1启用,2禁用
        imagePath: "",
        jumpUrl: "",
        description: "",
        sort: null
      },
      typeOption: [
        {
          id: 1,
          value: "banner"
        },
        {
          id: 2,
          value: "ico"
        }
      ],
      rules: {
        type: [
          { required: true, message: '类型不能为空', trigger: 'change' }
        ],
        isEnabled: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ],
        imagePath: [
          { required: true, message: '图片路径不能为空', trigger: 'blur' }
        ],
        jumpUrl: [
          { required: true, message: '跳转路径不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入显示顺序', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '描述信息不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 新增
    addBanner(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await addBannersApi(this.body)
          if (res.code === 200) {
            this.$message.success("新增banner成功")
            this.handleClose()
          } else {
            this.$message.error("新增banner失败")
          }
        } else {
          this.$message.warning("缺少必填项")
        }
      })

    },
    handleClose() {
      // 触发close事件
      this.$emit('close', false);
    },
    // 修改
    updateBanner(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await updateBannersApi(getBannerTypeCode(this.body))
          if (res.code === 200) {
            this.$message.success("修改banner图成功")
            this.handleClose()
          } else {
            this.$message.error("修改banner图失败")
          }
        } else {
          this.$message.warning("缺少必填项")
        }
      })

    },
    // 取消
    cancel() {
      this.handleClose()
    },
    // 确定
    submit(formName) {
      if (this.title === '新增banner图') {
        this.addBanner(formName)
      } else {
        this.updateBanner(formName)
      }
    },
    getBody() {
      if (this.title !== '修改banner图')
        return
      const { id, type, isEnabled, imagePath, jumpUrl, description, sort } = this.bannerInfo
      this.body = {
        id,
        type,
        isEnabled,
        imagePath,
        jumpUrl,
        description,
        sort
      }
    },
    beforeUpload(file) {
      console.log(file)
      this.uploadFile(file);
      return false; // 取消默认上传行为
    },
    uploadFile(file) {
      const formData = new FormData();
      // 如果 raw 是 undefined，则直接使用 file
      const fileToUpload = file.raw || file;
      formData.append('file', fileToUpload); // 添加文件流

      axios.post('https://api.whalelive.site/api/live/files/image/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          ...this.headers // 如果需要其他请求头
        }
      })
        .then(response => {
          console.log('上传成功', response.data);
        })
        .catch(error => {
          console.error('上传失败', error);
        });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      console.log(this.dialogImageUrl)
      this.imgDialogVisible = true;
    }
  },
  mounted() {
    this.getBody()
  },
}
</script>
<style lang="scss" scoped>
::v-deep .el-input__inner::-webkit-inner-spin-button,
.el-input__inner::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>